package cn.rslee.demo.spring.jpa.service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import cn.rslee.demo.spring.jpa.entity.AccessLog;
import cn.rslee.demo.spring.jpa.entity.DateParam;
import cn.rslee.demo.spring.jpa.repository.AccessLogCustomerRepository;

/**
 * 描述：
 * 
 * <pre>HISTORY
 * ****************************************************************************
 *  ID   DATE           PERSON          REASON
 *  1    2016年6月2日      325175         Create
 * ****************************************************************************
 * </pre>
 * @author 325175
 * @since 1.0
 */
@Component("accessLogCustomerService")
public class AccessLogCustomerServiceImpl implements AccessLogCustomerService{
	
	@Resource
	private AccessLogCustomerRepository accessLogCustomerRepository;

	@Override
	public Page<AccessLog> findByPage(int page, int size, String sysCode,
			String username, DateParam visitTmFrom, DateParam visitTmTo) {
		
		return accessLogCustomerRepository.findAll(getWhereClause(sysCode,username,visitTmFrom,visitTmTo),new PageRequest(page,size));
	}
	
	// 基于Specification的动态查询
	private Specification<AccessLog> getWhereClause(final String sysCode,
			final String username, final DateParam visitTmFrom, final DateParam visitTmTo){
		// 简单的select 语句。条件之间是通过and进行连接的
		return new Specification<AccessLog>() {
			public Predicate toPredicate(Root<AccessLog> root,
					CriteriaQuery<?> query, CriteriaBuilder builder) {
				
				List<Predicate> predicates = new ArrayList<Predicate>();
				if(!StringUtils.isEmpty(sysCode)){
					predicates.add(builder.notEqual(root.get("sysCode").as(String.class), sysCode));
				}
				if(!StringUtils.isEmpty(username)){
					predicates.add(builder.equal(root.get("username").as(String.class), username));
				}
				if(visitTmFrom != null && visitTmTo != null){
					predicates.add(builder.between(root.get("visitTm").as(Date.class), visitTmFrom.getDate(),visitTmTo.getDate()));
				}
				Predicate[] pre = new Predicate[predicates.size()];
                query.where(predicates.toArray(pre));
                return query.getRestriction();
			}
		};
		
	}

}
